package wcg;

import ikelib.NumericTextField;

import javax.swing.JPanel;
import java.awt.Frame;
import java.awt.BorderLayout;
import java.awt.Point;

import javax.swing.JDialog;
import java.awt.GridBagLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.UIManager;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import javax.swing.JTextPane;
import java.awt.SystemColor;

public class DialogFactor extends JDialog implements ActionListener, KeyListener {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JPanel jPanelSouth = null;
	private JButton jButtonOK = null;
	private JButton jButtonCancel = null;
	private JPanel jPanelCenter = null;
	private JLabel labelSensor = null;
	private JLabel jLabel1 = null;
	private NumericTextField jTextFieldSense = null;
	private JComboBox jComboBoxUnit = null;
	private JLabel labelAmplifier = null;
	private JLabel jLabel3 = null;
	private NumericTextField jTextFieldAmpGain = null;
	private JLabel labelDigitizer = null;
	private JLabel jLabel5 = null;
	private NumericTextField jTextFieldBit = null;
	private JComboBox jComboBoxFullscaleUnit = null;
	private JComboBox jComboBoxGainUnit = null;
	private JLabel jLabel6 = null;
	private NumericTextField jTextFieldFactor = null;
	private JLabel labelDisplay = null;
	private JLabel jLabel8 = null;
	private NumericTextField jTextFieldFullscale = null;
	private JLabel jLabel9 = null;
	private JTextField jTextFieldUnit = null;
	private JLabel jLabel10 = null;
	private JLabel jLabelFactorUnit = null;
	private JLabel jLabelStatus = null;
	private boolean retcode = false;
	private double Factor=0.0;
	private long FullScale=0L;
	/**
	 * @param owner
	 */
	public DialogFactor(Frame owner) {
		super(owner,true);
		initialize();
		setTitle("Set up physical conversion");
		if(owner!=null){
			Point p = owner.getLocationOnScreen();
			this.setLocation(p);
		}
		calculate();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(363, 588);
		this.setContentPane(getJContentPane());
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getJPanelSouth(), BorderLayout.SOUTH);  // Generated
			jContentPane.add(getJPanelCenter(), BorderLayout.CENTER);  // Generated
		}
		return jContentPane;
	}

	/**
	 * This method initializes jPanelSouth	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelSouth() {
		if (jPanelSouth == null) {
			jLabelStatus = new JLabel();
			jLabelStatus.setText("Status");  // Generated
			jLabelStatus.setBounds(new Rectangle(6, 2, 121, 22));  // Generated
			jPanelSouth = new JPanel();
			jPanelSouth.setLayout(null);  // Generated
			jPanelSouth.setPreferredSize(new Dimension(100,34));
			jPanelSouth.add(getJButtonOK(), null);  // Generated
			jPanelSouth.add(getJButtonCancel(), null);  // Generated
			jPanelSouth.add(jLabelStatus, null);  // Generated
		}
		return jPanelSouth;
	}

	/**
	 * This method initializes jButtonOK	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonOK() {
		if (jButtonOK == null) {
			jButtonOK = new JButton();
			jButtonOK.setBounds(new Rectangle(254, 1, 80, 26));  // Generated
			jButtonOK.setText("OK");  // Generated
			jButtonOK.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try{
						Factor = Double.valueOf(getFactorString());
						FullScale = Long.valueOf(getFullScaleString());
						retcode=true;
						setVisible(false);
					}
					catch(NumberFormatException ex){

					}
				}
			});
		}
		return jButtonOK;
	}
	public boolean getReturn(){
		return retcode;
	}
	public String getUnitString(){
		return jTextFieldUnit.getText();
	}
	public String getFactorString(){
		return jTextFieldFactor.getText();
	}
	public double getFactor(){
		return Factor;
	}
	public String getFullScaleString(){
		return jTextFieldFullscale.getText();
	}
	public long getFullScale(){
		return FullScale;
	}
	/**
	 * This method initializes jButtonCancel	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonCancel() {
		if (jButtonCancel == null) {
			jButtonCancel = new JButton();
			jButtonCancel.setBounds(new Rectangle(166, 3, 80, 26));  // Generated
			jButtonCancel.setText("Cancel");  // Generated
			jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					setVisible(false);
				}
			});
		}
		return jButtonCancel;
	}

	/**
	 * This method initializes jPanelCenter	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelCenter() {
		if (jPanelCenter == null) {



			jPanelCenter = new JPanel();
			jPanelCenter.setLayout(null);

			JPanel panelResult = new JPanel();
			panelResult.setBorder(new TitledBorder(null, "Result", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			panelResult.setBounds(15, 361, 326, 126);
			jPanelCenter.add(panelResult);
			panelResult.setLayout(null);


			jLabel6 = new JLabel();
			jLabel6.setBounds(12, 52, 58, 21);
			panelResult.add(jLabel6);
			jLabel6.setText("Factor");  // Generated
			panelResult.add(getJTextFieldFactor());
			jLabel8 = new JLabel();
			jLabel8.setBounds(12, 86, 58, 21);
			panelResult.add(jLabel8);
			jLabel8.setText("Fullscale");
			panelResult.add(getJTextFieldFullscale());
			jLabel9 = new JLabel();
			jLabel9.setBounds(12, 21, 58, 21);
			panelResult.add(jLabel9);
			jLabel9.setText("Unit");  // Generated
			panelResult.add(getJTextFieldUnit());
			jLabel10 = new JLabel();
			jLabel10.setBounds(247, 89, 48, 21);
			panelResult.add(jLabel10);
			jLabel10.setText("digit");  // Generated
			jLabelFactorUnit = new JLabel();
			jLabelFactorUnit.setBounds(247, 52, 58, 21);
			panelResult.add(jLabelFactorUnit);
			jLabelFactorUnit.setText("digit");  // Generated

			JPanel panelDigitizer = new JPanel();
			panelDigitizer.setBorder(new TitledBorder(null, "Digitizer", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			panelDigitizer.setBounds(12, 193, 326, 125);
			jPanelCenter.add(panelDigitizer);
			panelDigitizer.setLayout(null);
			jLabel5 = new JLabel();
			jLabel5.setBounds(9, 28, 98, 22);
			panelDigitizer.add(jLabel5);
			jLabel5.setText("quantization bit");
			panelDigitizer.add(getJTextFieldBit());
			panelDigitizer.add(getJComboBoxFullscaleUnit());
			jLabel51 = new JLabel();
			jLabel51.setBounds(10, 92, 101, 21);
			panelDigitizer.add(jLabel51);
			jLabel51.setText("quantization step");  // Generated
			panelDigitizer.add(getJTextFieldStep());
			jLabel11 = new JLabel();
			jLabel11.setBounds(258, 87, 45, 20);
			panelDigitizer.add(jLabel11);
			jLabel11.setText("V/digit");  // Generated

			JLabel lblAmplitude = new JLabel();
			lblAmplitude.setText("Voltage Range");
			lblAmplitude.setBounds(9, 60, 101, 21);
			panelDigitizer.add(lblAmplitude);

			textFieldVoltageRange = new NumericTextField();
			textFieldVoltageRange.addKeyListener(new KeyAdapter() {
				@Override
				public void keyTyped(KeyEvent arg0) {
					int cod = arg0.getKeyCode();
					if(cod==KeyEvent.VK_ENTER){
						calcDigitizerFactorFromMaxVoltage();
					}
				}

			});
			textFieldVoltageRange.addFocusListener(new FocusAdapter() {
				@Override
				public void focusLost(FocusEvent arg0) {
					calcDigitizerFactorFromMaxVoltage();
				}
			});
			textFieldVoltageRange.setToolTipText("Maximun voltage(zero to peek) ");
			textFieldVoltageRange.setText("8.16");
			textFieldVoltageRange.setBounds(121, 59, 129, 23);
			panelDigitizer.add(textFieldVoltageRange);

			JLabel lblV = new JLabel();
			lblV.setText("V");
			lblV.setBounds(258, 60, 45, 20);
			panelDigitizer.add(lblV);

			JPanel panelAmplifier = new JPanel();
			panelAmplifier.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Amplifier", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			panelAmplifier.setBounds(12, 129, 326, 53);
			jPanelCenter.add(panelAmplifier);
			panelAmplifier.setLayout(null);


			jLabel3 = new JLabel();
			jLabel3.setBounds(12, 24, 70, 19);
			panelAmplifier.add(jLabel3);
			jLabel3.setText("Gain");
			panelAmplifier.add(getJTextFieldAmpGain());
			panelAmplifier.add(getJComboBoxGainUnit());

			JPanel panelSensor = new JPanel();
			panelSensor.setBorder(new TitledBorder(null, "Sensor", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			panelSensor.setBounds(12, 10, 326, 109);
			jPanelCenter.add(panelSensor);
			panelSensor.setLayout(null);


			jLabel1 = new JLabel();
			jLabel1.setBounds(11, 23, 70, 19);
			panelSensor.add(jLabel1);
			jLabel1.setText("Sensitivity");
			panelSensor.add(getJTextFieldSense());
			panelSensor.add(getJComboBoxUnit());
			
			JTextPane txtpng = new JTextPane();
			txtpng.setToolTipText("Copy and paste");
			txtpng.setBackground(SystemColor.info);
			txtpng.setText("Note. 1G = 9.80665 m/s/s = 980.665 gal \r\n");
			txtpng.setBounds(13, 66, 294, 24);
			panelSensor.add(txtpng);
			jPanelCenter.add(getBtnNewButton());
		}
		return jPanelCenter;
	}
	
	
	/**
	 * 
	 */
	protected void calcDigitizerFactorFromMaxVoltage() throws NumberFormatException {
		
		if(textFieldVoltageRange==null) return;
		double volt  = Double.valueOf(textFieldVoltageRange.getText());
		int bit = Integer.valueOf(jTextFieldBit.getText());
		double resolution = volt / Math.pow(2.0,bit-1);
		jTextFieldStep.setText(String.format("%e",resolution));
	}
	protected void calcMaxVoltageFromDigitizerFactor() throws NumberFormatException{
		if(textFieldVoltageRange==null) return;
		double step  = Double.valueOf(jTextFieldStep.getText());
		int bit = Integer.valueOf(jTextFieldBit.getText());
		double volt = step * Math.pow(2.0,bit-1);
		textFieldVoltageRange.setText(String.format("%5.2f",volt));
	}

	/**
	 * This method initializes jTextFieldSense	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldSense() {
		if (jTextFieldSense == null) {
			jTextFieldSense = new NumericTextField();
			jTextFieldSense.setBounds(89, 21, 119, 28);
			jTextFieldSense.setText("2");
			jTextFieldSense.setToolTipText("Sensor sensitivity.");
			jTextFieldSense.addKeyListener(this);
		}
		return jTextFieldSense;
	}
	private String OrgUnitString = new String();
	/**
	 * This method initializes jComboBoxUnit	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getJComboBoxUnit() {
		if (jComboBoxUnit == null) {
			jComboBoxUnit = new JComboBox();
			jComboBoxUnit.setBounds(215, 23, 90, 22);
			String[] data = {"V/g","V/gal","V/m/s/s","V/kine","V/m/s"};
			for(int i=0;i<data.length;i++){
				jComboBoxUnit.addItem(data[i]);
			}
			jComboBoxUnit.setSelectedIndex(0);
			OrgUnitString=data[0];
			jComboBoxUnit.addActionListener(this);
		}
		return jComboBoxUnit;
	}

	/**
	 * This method initializes jTextFieldAmpGain	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldAmpGain() {
		if (jTextFieldAmpGain == null) {
			jTextFieldAmpGain = new NumericTextField();
			jTextFieldAmpGain.setBounds(123, 19, 86, 24);
			jTextFieldAmpGain.setText("1");
			jTextFieldAmpGain.setToolTipText("<html>Amplifier gain.<br><br>Vout/Vin or 20log(Vout/Vin) dB.<br>If not use amplifier then set 1</html>");
			jTextFieldAmpGain.addKeyListener(this);

		}
		return jTextFieldAmpGain;
	}

	/**
	 * This method initializes jTextFieldBit	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldBit() {
		if (jTextFieldBit == null) {
			jTextFieldBit = new NumericTextField();
			jTextFieldBit.setBounds(120, 26, 59, 24);
			jTextFieldBit.setText("24");
			jTextFieldBit.setToolTipText("A/D Converter bit width or max value(0-max)");
			jTextFieldBit.addKeyListener(this);
		}
		return jTextFieldBit;
	}

	/**
	 * This method initializes jComboBoxFullscaleUnit	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getJComboBoxFullscaleUnit() {
		if (jComboBoxFullscaleUnit == null) {
			jComboBoxFullscaleUnit = new JComboBox();
			jComboBoxFullscaleUnit.setBounds(191, 28, 112, 22);
			String[] data = {"bit","digit"};
			for(int i=0;i<data.length;i++){
				jComboBoxFullscaleUnit.addItem(data[i]);
			}
			jComboBoxFullscaleUnit.setSelectedIndex(0);
			jComboBoxFullscaleUnit.addActionListener(this);
		}
		return jComboBoxFullscaleUnit;
	}

	/**
	 * This method initializes jComboBoxGainUnit	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getJComboBoxGainUnit() {
		if (jComboBoxGainUnit == null) {
			jComboBoxGainUnit = new JComboBox();
			jComboBoxGainUnit.setBounds(216, 20, 90, 23);
			String[] data = {" ","dB"};
			for(int i=0;i<data.length;i++){
				jComboBoxGainUnit.addItem(data[i]);
			}
			jComboBoxGainUnit.setSelectedIndex(0);
			jComboBoxGainUnit.addActionListener(this);
		}
		return jComboBoxGainUnit;
	}

	/**
	 * This method initializes jTextFieldFactor	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldFactor() {
		if (jTextFieldFactor == null) {
			jTextFieldFactor = new NumericTextField();
			jTextFieldFactor.setBounds(123, 50, 112, 25);
		}
		return jTextFieldFactor;
	}

	/**
	 * This method initializes jTextFieldFullscale	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldFullscale() {
		if (jTextFieldFullscale == null) {
			jTextFieldFullscale = new NumericTextField();
			jTextFieldFullscale.setBounds(123, 85, 112, 24);
		}
		return jTextFieldFullscale;
	}

/**
	 * This method initializes jTextFieldUnit	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldUnit() {
		if (jTextFieldUnit == null) {
			jTextFieldUnit = new JTextField();
			jTextFieldUnit.setBounds(123, 20, 112, 23);
		}
		return jTextFieldUnit;
	}
	private int Counter=0;
	private JLabel jLabel51 = null;
	private NumericTextField jTextFieldStep = null;
	private JLabel jLabel11 = null;
	private NumericTextField textFieldVoltageRange;
	private void calculate(){

		String unit = "";
		double factor = 0.0;
		double digit = 0.0;
		double gain = 1.0;
		double step = 1.0;

		try{
			//calcDigitizerFactorFromMaxVoltage();
			// FullScale
			String digistr = (String)jComboBoxFullscaleUnit.getSelectedItem();
			long fs = Long.parseLong(jTextFieldBit.getText());
			if(digistr.compareTo("bit")==0){
				digit = Math.pow(2.0, fs); 
			}
			else{
				digit = fs;
			}
			// step
			String stepstr  = jTextFieldStep.getText();
			step = Double.valueOf(stepstr);

			// gain
			String gainunit = (String)jComboBoxGainUnit.getSelectedItem();
			String gainstr  = jTextFieldAmpGain.getText();
			gain = Double.valueOf(gainstr);
			if(gainunit.compareTo("dB")==0){
				gain = Math.pow(10.0, gain/20.0);
			}
			// Unit 
			String sense = (String)jComboBoxUnit.getSelectedItem();
			String sen = (String)jTextFieldSense.getText();
			// {"V/g","V/gal","V/m/s**2","V/cm/s**2","V/kine"};
			Double sensor = Double.parseDouble(sen);
			factor = step / sensor / gain;
			if(sense.compareTo("V/g")==0){
				unit = "g";
			}
			else if(sense.compareTo("V/gal")==0){
				unit = "gal";
			}
			else if(sense.compareTo("V/m/s**2")==0){
				unit = "m/s**2";
			}
			else if(sense.compareTo("V/kine")==0){
				unit = "kine";
			}
			else if(sense.compareTo("V/m/s")==0){
				unit = "m/s";
			}
		}
		catch (NumberFormatException e){
			jTextFieldUnit.setText("");
			jTextFieldFactor.setText("");
			jTextFieldFullscale.setText("");
			jLabelFactorUnit.setText("/digit");
			jLabelStatus.setText(String.format(" Error "));
			return;
		}

		jTextFieldUnit.setText(unit);
		jTextFieldFactor.setText(String.format("%2.6e",factor));
		jTextFieldFullscale.setText(String.format("%d",(long)digit/2L));
		jLabelFactorUnit.setText(unit+"/digit");
		jLabelStatus.setText(String.format("Auto calc count=%2d",(Counter++)%100));
	}

	private static final double ConstG2gal = 980.665;
	private static final double ConstG2mss = 9.80665;
	private JButton btnNewButton;

	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		
		// 単位の変換を自動的に行うのだ
		
		if(arg0.getSource().equals(jComboBoxUnit)){
			//OrgUnitString
			//  {"V/g","V/gal","V/m/s/s","V/kine","V/m/s"};
			String ns = (String)jComboBoxUnit.getSelectedItem();
			// もし変化があれば
			if(ns.compareTo(OrgUnitString) != 0){
				Double va = Double.valueOf(jTextFieldSense.getText());
				if(OrgUnitString.compareTo("V/g")==0){
					if(ns.compareTo("V/gal")==0){
						va /= ConstG2gal;
					}
					else if(ns.compareTo("V/m/s/s")==0){
						va /= ConstG2mss;
					}
				}
				else if (OrgUnitString.compareTo("V/gal")==0){
					if(ns.compareTo("V/g")==0){
						va *= ConstG2gal;
					}
					else if(ns.compareTo("V/m/s/s")==0){
						va *= ConstG2gal;
						va /= ConstG2mss;
					}
					
				}
				else if (OrgUnitString.compareTo("V/m/s/s")==0){
					if(ns.compareTo("V/gal")==0){
						va *= ConstG2mss;
						va /= ConstG2gal;
					}
					else if(ns.compareTo("V/g")==0){
						va *= ConstG2mss;
					}
					
				}
				OrgUnitString=ns;
				jTextFieldSense.setText(String.format("%e",va));
			}
		}
		calculate();

	}

	@Override
	public void keyPressed(KeyEvent e) {

	}

	@Override
	public void keyReleased(KeyEvent e) {
		calculate();

	}

	@Override
	public void keyTyped(KeyEvent e) {
	}

	/**
	 * This method initializes jTextFieldStep	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldStep() {
		if (jTextFieldStep == null) {
			jTextFieldStep = new NumericTextField();
			jTextFieldStep.addKeyListener(new KeyAdapter() {
				@Override
				public void keyTyped(KeyEvent e) {
					int cod = e.getKeyCode();
					if(cod==KeyEvent.VK_ENTER){
						calcMaxVoltageFromDigitizerFactor();
					}
				}
			});
			jTextFieldStep.addFocusListener(new FocusAdapter() {
				@Override
				public void focusLost(FocusEvent e) {
					calcMaxVoltageFromDigitizerFactor();

				}
			});
			jTextFieldStep.setBounds(121, 90, 129, 23);
			jTextFieldStep.setToolTipText("Voltage per digit.");
			jTextFieldStep.setText("9.727478e-07");
			jTextFieldStep.addCaretListener(new javax.swing.event.CaretListener() {
				public void caretUpdate(javax.swing.event.CaretEvent e) {
					calculate();
				}
			});

		}
		return jTextFieldStep;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("calculate");
			btnNewButton.setToolTipText("force calculate");
			btnNewButton.setBounds(219, 328, 108, 28);
		}
		return btnNewButton;
	}
}  //  @jve:decl-index=0:visual-constraint="10,10"
